package com.yeyks.service.impl;

import com.yeyks.service.CczcService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author fuchangshuai
 * @date 2019/4/8 5:20 PM
 */
@Service
@Slf4j
public class CczcServiceImpl implements CczcService {

    @Value("${cczc.config.clientId}")
    String clientId;

    @Value("${cczc.config.signKey}")
    String signKey;

    @Override
    public Map<String, String> getSign(Integer userId) {
        long time = new Date().getTime();
        Map<String, Object> params = new HashMap<>();
        params.put("client_id", clientId);
        params.put("ext_user_id", String.valueOf(userId));
        params.put("sign_key", signKey);
        params.put("timestamp", String.valueOf(time));
        Map<String, String> map = new HashMap<>();
        map.put("timestamp", String.valueOf(time));
        map.put("sign", sign(params));
        return map;
    }

    public String sign(Map<String, Object> params) {

        Map<String, Object> result = new LinkedHashMap<>();
        params.entrySet().stream()
                .sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> entry : result.entrySet()) {
            sb.append(entry.getKey()).append(entry.getValue());
        }
        return DigestUtils.sha1Hex(sb.toString());
    }

//    public static void main(String[] args) {
//        Map<String, Object> params = new HashMap<>();
//        params.put("ext_user_id", "1234");
//        params.put("clientId", "84e7939bbdab8c76");
//        params.put("timestamp", "1508240915308");
//        params.put("sign_key", "567807b69f7047c9750ade8e471452ec");
//        CczcServiceImpl cczcService = new CczcServiceImpl();
//        String sign = cczcService.sign(params);
//    }

}
